/**
 * @desc 常用公共方法工具类
 * @author Yisin
 */
function CommonUtil() {
}

CommonUtil.getUniqueId = function(ops) {
	return (ops == undefined ? '' : ops) + new Date().getTime()
			+ Math.ceil(Math.random() * 999);
};

CommonUtil.getBrowser = function() {
	var browe = window.navigator.appName == "Microsoft Internet Explorer" ? 'ie'
			: 'nonie';
	return browe;
};

CommonUtil.getLevel = function(n) {
	return n * 10000;
};

CommonUtil.setAlpha = function(dom, al) {
	if (this.getBrowser() == 'ie') {
		dom.style.filter = 'alpha(opacity=' + (al * 100) + ')';
	}
	dom.style.opacity = al;
	dom.style.MozOpacity = al;
};

CommonUtil.browserIsReady = function() {
	// interactive
	return document.readyState == 'complete';
};

CommonUtil.windowWidth = function() {
	return CommonUtil.getBrowser() == 'ie' ? $(document).width() : $(window)
			.width();
	/*
	 * if (CommonUtil.browserIsReady()) { } else { return window.screen.width; }
	 */

};

CommonUtil.windowHeight = function() {
	return CommonUtil.getBrowser() == 'ie' ? $(document).height() : $(window)
			.height();
	/*
	 * if (CommonUtil.browserIsReady()) { } else { return window.screen.height; }
	 */

};

CommonUtil.isScreen = function() {
	var wh = CommonUtil.windowHeight();
	var sh = window.screen.height;
	return sh - wh < 5;
};

CommonUtil.createDom = function(ops) {
	var dom = null;
	if (ops != undefined) {
		dom = document.createElement(ops.tagName);
		// 属性
		for ( var i in ops.attr) {
			if (ops.attr[i] != undefined) {
				dom[i] = ops.attr[i];
			}
		}
		// 样式
		for ( var i in ops.style) {
			if (ops.style[i] != undefined) {
				dom.style[i] = ops.style[i];
			}
		}
		//
		if (ops.html != undefined) {
			dom.innerHTML = ops.html;
		}
		if (ops.text != undefined) {
			dom.innerText = ops.text;
		}
		// 事件
		if (ops.events != undefined) {
			// 样式
			for ( var i in ops.events) {
				if (ops.events[i] != undefined) {
					$(dom).bind(i, ops.events[i]);
				}
			}
		}
	}
	return dom;
};

CommonUtil.fontHtml = function(text, ops) {
	var defau = {
		size : '3px',
		color : '#ffffff',
		face : 'Arial'
	};
	if (ops == undefined || typeof (ops) != 'object') {
		ops = defau;
	}
	var font = '<font';
	for ( var attr in ops) {
		if (ops[attr] != undefined) {
			font += ' ' + attr + '="' + ops[attr] + '"';
		}
	}
	return font += '>' + text + '</font>';
};

/** ********** 获取页面?后面的参数 ************ */
CommonUtil.getRequestParam = function(attr) {
	var url = location.search;
	// 获取url中"?"符后的字串
	var theRequest = new Object();
	if (url.indexOf("?") != -1) {
		var str = url.substr(1);
		var strs = str.split("&");
		for ( var i = 0; i < strs.length; i++) {
			var params = strs[i].split("=");
			if (attr == params[0]) {
				theRequest = params[1];
				break;
			}
			theRequest[params[0]] = unescape(params[1]);
		}
	}
	return theRequest;
};

CommonUtil.weekArray = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
CommonUtil.formatTime = function(fmt, date) {
	date = date == undefined ? new Date() : date;
	var dstr = '';
	if (fmt != undefined && fmt != null) {
		fmt = fmt.replace('yyyy', date.getFullYear());
		fmt = fmt.replace('YYYY', date.getFullYear());
		// 月份
		if (fmt.indexOf('MM') != -1) {
			fmt = fmt.replace('MM', (date.getMonth() + 1) < 10 ? '0'
					+ (date.getMonth() + 1) : (date.getMonth() + 1));
		}
		if (fmt.indexOf('MM') == -1 && fmt.indexOf('M') != -1) {
			fmt = fmt.replace('M', (date.getMonth() + 1));
		}
		// 日期
		if (fmt.indexOf('dd') != -1) {
			fmt = fmt.replace('dd', date.getDate() < 10 ? '0' + date.getDate()
					: date.getDate());
		}
		if (fmt.indexOf('dd') == -1 && fmt.indexOf('d') != -1) {
			fmt = fmt.replace('d', date.getDate());
		}
		// 小时
		if (fmt.indexOf('HH') != -1) {
			fmt = fmt.replace('HH', date.getHours() < 10 ? '0'
					+ date.getHours() : date.getHours());
		}
		if (fmt.indexOf('HH') == -1 && fmt.indexOf('H') != -1) {
			fmt = fmt.replace('H', date.getHours());
		}
		// 分钟
		if (fmt.indexOf('mm') != -1) {
			fmt = fmt.replace('mm', date.getMinutes() < 10 ? '0'
					+ date.getMinutes() : date.getMinutes());
		}
		if (fmt.indexOf('mm') == -1 && fmt.indexOf('m') != -1) {
			fmt = fmt.replace('m', date.getMinutes());
		}
		// 秒钟
		if (fmt.indexOf('ss') != -1) {
			fmt = fmt.replace('ss', date.getSeconds() < 10 ? '0'
					+ date.getSeconds() : date.getSeconds());
		}
		if (fmt.indexOf('ss') == -1 && fmt.indexOf('s') != -1) {
			fmt = fmt.replace('s', date.getSeconds());
		}
		fmt = fmt.replace('ww', CommonUtil.weekArray[date.getDay()]);
		fmt = fmt.replace('w', date.getDay());
		dstr = fmt;
	} else {
		dstr = date.getFullYear() + '-' + (date.getMonth() + 1) + '-'
				+ date.getDate();
		dstr += ' ' + date.getHours() + ':' + date.getMinutes() + ':'
				+ date.getSeconds();
	}
	return dstr;
};

CommonUtil.containByArray = function(array, e) {
	for (i = 0; i < array.length; i++) {
		if (array[i] == e) {
			return true;
		}
	}
	return false;
};

CommonUtil.isEmpty = function(str) {
	return str == undefined || str == null || str == '';
};

CommonUtil.isNulls = function(str) {
	return str == undefined || str == null;
};

CommonUtil.isEmptyStr = function(str) {
	return str == undefined || str == null || str == '' || str == 'null'
			|| str == 'undefined';
};

CommonUtil.isNotEmpty = function(str) {
	return !CommonUtil.isEmpty(str);
};

CommonUtil.isNotNulls = function(str) {
	return !CommonUtil.isNulls(str);
};

CommonUtil.isNotEmptyStr = function(str) {
	return !CommonUtil.isEmptyStr(str);
};

/**
 * 将空null、undefined转换为""
 * 
 * @param str
 * @param nullstr
 * @returns
 */
CommonUtil.coverStr1 = function(str, nullstr) {
	if (CommonUtil.isNulls(str)) {
		str = nullstr || '';
	}
	return str;
};

/**
 * 将空null、undefined转换为""
 * 
 * @param str
 * @param nullstr
 * @returns
 */
CommonUtil.coverStr2 = function(str, nullstr) {
	str = CommonUtil.coverStr1(str);
	if (CommonUtil.isEmptyStr(str)) {
		str = nullstr || '';
	}
	return str;
};

/**
 * 转码，将字符串（汉字）转码
 * 
 * @param param
 */
CommonUtil.coding = function(param) {
	if (param != undefined && param != null) {
		param = encodeURI(encodeURI(param));
	}
	return param;
};

/**
 * 将文本中回车换行符\n替换成<br>
 * 标签
 * 
 * @param param
 */
CommonUtil.replaceEnter = function(param) {
	if (!CommonUtil.isEmpty(param)) {
		while (param.indexOf('\n') != -1) {
			param = param.replace('\n', '<br>');
		}
	}
	return param;
};

/**
 * 将文本中<br>
 * 标签替换成回车换行符\n
 * 
 * @param param
 */
CommonUtil.replaceBr = function(param) {
	if (!CommonUtil.isEmpty(param)) {
		while (param.indexOf('<br>') != -1 || param.indexOf('<BR>') != -1) {
			param = param.replace('<br>', '\n');
			param = param.replace('<BR>', '\n');
		}
	}
	return param;
};

/**
 * 替换字符
 * 
 * @param sourse
 *            多个用|分隔
 * @param target
 * @returns
 */
CommonUtil.replaceAll = function(sourse, reg, target) {
	if (!CommonUtil.isEmpty(sourse) && !CommonUtil.isNulls(reg)
			&& !CommonUtil.isNulls(target)) {
		if (reg.indexOf('|') != -1) {
			var rou = reg.split('|');
			for ( var i = 0; i < rou.length; i++) {
				while (sourse.indexOf(rou[i]) != -1) {
					sourse = sourse.replace(rou[i], target);
				}
			}
		} else {
			while (sourse.indexOf(reg) != -1) {
				sourse = sourse.replace(reg, target);
			}
		}
	}
	return sourse;
};

/**
 * 将脚本转换为可以在页面正常显示与传值的符号<br>
 * 例如：': &apos; ": &quot; <: &lt; >: &gt; &: æ %: <br>
 * 备用符号：æɔəʃθðʒ
 * 
 * @param str
 */
CommonUtil.coverScriptByHtml = function(str) {
	if (!CommonUtil.isEmpty(str)) {
		try {
			// 替换回车符
			str = CommonUtil.replaceEnter(str);
			str = CommonUtil.replaceAll(str, "'", 'æapos;');
			str = CommonUtil.replaceAll(str, '"', 'æquot;');
			str = CommonUtil.replaceAll(str, '<', 'ælt;');
			str = CommonUtil.replaceAll(str, '%', 'ʃ');
			str = CommonUtil.replaceAll(str, '+', 'θ');
			str = CommonUtil.replaceAll(str, '  ', ' ');
		} catch (e) {
			new Error('转换出错！');
		}
	}
	return str;
};

/**
 * 获取元素的绝对位置
 * 
 * @param obj
 * @returns {left,top}
 */
CommonUtil.getPosition = function(obj) {
	obj = obj == undefined ? new Object() : obj;
	var t = obj.offsetTop;
	var l = obj.offsetLeft;
	while (obj = obj.offsetParent) {
		t += obj.offsetTop;
		l += obj.offsetLeft;
	}

	var xl = 0, yt = 0;
	if (typeof window.pageYOffset != 'undefined') {
		xl = window.pageXOffset;
		yt = window.pageYOffset;
	}
	// 如果浏览器支持 compatMode, 并且指定了 DOCTYPE, 通过 documentElement 获取滚动距离作为页面和视窗间的距离
	// IE 中, 当页面指定 DOCTYPE, compatMode 的值是 CSS1Compat, 否则 compatMode 的值是
	// BackCompat
	else if (typeof document.compatMode != 'undefined'
			&& document.compatMode != 'BackCompat') {
		xl = document.documentElement.scrollLeft;
		yt = document.documentElement.scrollTop;
	}
	// 如果浏览器支持 document.body, 可以通过 document.body
	// 来获取滚动高度，如果是在ifram里面，用document.body可以获取iframe中滚动条的位置。
	else if (typeof document.body != 'undefined') {
		xl = document.body.scrollLeft;
		yt = document.body.scrollTop;
	}
	l = (l - xl);
	t = (t - yt);
	var pam = {
		left : +l,
		top : +t
	};
	return pam;
};

// 添加cookie
CommonUtil.addCookie = function(name, value, expiresDay) {
	var cookieString = name + "=" + escape(value);
	// 判断是否设置过期时间
	if (expiresDay > 0) {
		var days = new Date();
		days.setTime(days.getTime() + (expiresDay * 24 * 60 * 60 * 1000));
		cookieString = cookieString + "; expires=" + days.toGMTString();
	}
	document.cookie = cookieString;
};

// 获取cookie值
CommonUtil.getCookie = function(name) {
	var strCookie = document.cookie;
	var arrCookie = strCookie.split("; ");
	for ( var i = 0; i < arrCookie.length; i++) {
		var arr = arrCookie[i].split("=");
		if (arr[0] == name)
			return unescape(arr[1]);
	}
	return "";
};

// 删除指定cookie
CommonUtil.deleteCookie = function(name) {
	var date = new Date();
	date.setTime(date.getTime() - 10000);
	document.cookie = name + "=v; expires=" + date.toGMTString();
};

CommonUtil.getStrLeng = function(str) {
	return str.replace(/[\u0391-\uFFE5]/g, "aa").length;
};

CommonUtil.strSubstring = function(str, len) {
	if (str && str.length > len) {
		str = str.substring(0, len) + "...";
	}
	return str;
};

CommonUtil.formatDateStr = function(dateStr) {
	var date = null;
	if (dateStr) {
		dateStr = dateStr.replace(/[-]+/g, "\/");
		date = new Date(dateStr);
	}
	return date;
};

CommonUtil.compareTime = function(d) {
	var date = typeof (d) == 'string' ? CommonUtil.formatDateStr(d) : d;
	var comtime = date.getTime() - new Date().getTime();
	return comtime > 0;
};

CommonUtil.ComputTimeInterval = function(date) {
	var today = new Date().getTime(), today = (today - (date || 0)) / 1000;
	if (today <= 60) { // 1分钟以内
		date = "刚刚";
	} else if (today > 60 && today <= 60 * 60) {
		date = Math.floor(today / (60)) + "分钟前";
	} else if (today >= 60 * 60 && today <= 60 * 60 * 24) {
		date = Math.floor(today / (60 * 60)) + "小时前";
	} else if (today >= 60 * 60 * 24 && today <= 60 * 60 * 24 * 30) {
		date = Math.floor(today / (60 * 60 * 24)) + "个天前";
	} else if (today >= 60 * 60 * 24 * 30 && today <= 60 * 60 * 24 * 30 * 12) {
		date = Math.floor(today / (60 * 60 * 24 * 30)) + "月前";
	} else {
		date = "-";
	}
	return date;
};

CommonUtil.UUID = function(l, r) {
	var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
			.split('');
	var createUUID = function(len, radix) {
		var chars = CHARS, uuid = [], i;
		radix = radix || chars.length;
		if (len) {
			// Compact form
			for (i = 0; i < len; i++)
				uuid[i] = chars[0 | Math.random() * radix];
		} else {
			// rfc4122, version 4 form
			var r;
			// rfc4122 requires these characters
			uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
			uuid[14] = '4';
			// Fill in random data. At i==19 set the high bits of clock sequence
			// as
			// per rfc4122, sec. 4.1.5
			for (i = 0; i < 36; i++) {
				if (!uuid[i]) {
					r = 0 | Math.random() * 16;
					uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
				}
			}
		}
		return uuid.join('');
	};
	return createUUID(l, r);
};

CommonUtil.jspwd = function(p) {
	var s = p, a = p.split(''), b, c;
	for ( var i = 0; i < a.length; i++) {
		for ( var j = 0; j < a.length; j++) {
			b = s.substring(j);
			c = s.substring(0, j);
			s = b + c + a[j] + '' + i;
		}
	}
	s = s + (700 + p.length);
	return s;
};

CommonUtil.getServerAddress = function() {
	var address = "";
	try {
		var href = document.location.href;
		var end = href.indexOf('/', 10);
		if (end != -1) {
			address = href.substring(0, end) + "/";
		}
	} catch (e) {
		address = "";
	}
	return address;
};

CommonUtil.asyncLoadJs = function(jspath) {
	var oHead = document.getElementsByTagName('head').item(0); 
    var oScript = document.createElement("script"); 
    oScript.type = "text/javascript"; 
    oScript.src = jspath; 
    oHead.appendChild(oScript); 
};

CommonUtil.asyncLoadCss = function(csspath) {
	var oHead = document.getElementsByTagName('head').item(0); 
    var oLink = document.createElement("link"); 
    oLink.type = "text/css"; 
    oLink.rel = "sheetstyle"; 
    oLink.href = csspath; 
    oHead.appendChild(oLink); 
};
